<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="jobType">
        <el-select
          v-model="queryParams.jobType"
          placeholder="请选择任务类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.synchronous_tasktype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.taskstatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['console:dataTaskconf:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['console:dataTaskconf:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['console:dataTaskconf:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['console:dataTaskconf:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataTaskconfList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" align="center" width="55">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"></span>
        </template>
      </el-table-column>
      <el-table-column label="编号" prop="id" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务模式" align="center" prop="taskType" />
      <el-table-column label="任务类型" align="center" prop="jobType">
        <template slot-scope="scope">
          <div v-for="dict in dict.type.synchronous_tasktype" :key="dict.value">
            <!-- {{ dict.value ==  ? dict.label : "" }} -->
            {{ dict.value == scope.row.jobType ? dict.label : "" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="源实例名" align="center" prop="sourceName" />
      <el-table-column label="目标实例名" align="center" prop="sinkName" />
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <span v-for="dict in dict.type.taskstatus" :key="dict.value">
            <el-tag
              v-if="scope.row.taskStatus == dict.value"
              :type="dict.raw.listClass"
            >
              {{ dict.label }}
            </el-tag>
          </span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleExecute(scope.row)"
            v-if="scope.row.taskStatus != 0"
            v-hasPermi="['console:dataTaskconf:execute']"
            style="color: #42d885"
            >执行</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleResult(scope.row)"
            v-hasPermi="['console:tasks:result']"
            >记录</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleTaskResult(scope.row)"
            v-hasPermi="['console:dataTaskconf:execute']"
            v-if="scope.row.taskStatus == 2"
            >结果</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleResultLog(scope.row)"
            v-hasPermi="['console:tasks:resultLog']"
            >日志</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleScheduler(scope.row)"
            v-hasPermi="['console:dataTaskconf:scheduler']"
            >启动调度器</el-button
          > -->

          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.taskStatus != 0"
            v-hasPermi="['console:dataTaskconf:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['console:dataTaskconf:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pgNum"
      :limit.sync="queryParams.pgSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="jobMode">
          <el-select v-model="form.jobMode" placeholder="请选择任务类型">
            <el-option
              v-for="dict in dict.type.synchronous_jobmode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="源数据库name" prop="sourceName">
          <el-input
            v-model="form.sourceName"
            placeholder="请输入源数据库name"
          />
        </el-form-item>
        <el-form-item label="目标数据库name" prop="sinkName">
          <el-input
            v-model="form.sinkName"
            placeholder="请输入目标数据库name"
          />
        </el-form-item>
        <el-form-item label="任务调度器" prop="jobId">
          <el-input v-model="form.jobId" placeholder="请输入任务调度器" />
        </el-form-item>
        <el-form-item
          label="CDC配置
"
          prop="cdcId"
        >
          <el-input
            v-model="form.cdcId"
            placeholder="请输入CDC配置
"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.data_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="同步日志"
      :before-close="handleClose"
      :visible.sync="isLog"
      width="45%"
      destroy-on-close
      append-to-body
    >
      <div class="textBox" ref="logBox" v-show="logFofText.length > 0">
        <p
          v-for="(item, index) in logFofText"
          :style="{ color: item.logLevel == 'error' ? 'red' : false }"
          :key="index"
        >
          {{ item.text }}
        </p>
      </div>
      <el-empty
        description="暂无日志"
        v-show="logFofText.length < 1"
      ></el-empty>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEnter">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="同步结果"
      :visible.sync="asyncResult"
      width="75%"
      destroy-on-close
      v-if="asyncResultTable"
    >
      <div>
        <p>任务类型：{{ asyncResultTable.dataType }}</p>
        <p>任务信息：{{ asyncResultTable.message }}</p>
      </div>
      <el-table :data="asyncResultTable.items" height="300">
        <el-table-column label="对象名称" prop="objectName" />
        <el-table-column label="信息" prop="message" />
        <el-table-column label="堆栈错误信息" align="center" prop="errors">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleStack(scope.row)"
              v-hasPermi="['console:dataTaskconf:stack']"
              >查看堆栈</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="对象类型" align="center" prop="type">
          <template slot-scope="scope">
            <span
              v-for="dict in dict.type.appraise_taskmode"
              :key="dict.value"
              >{{ scope.row.type == dict.value ? dict.label : "" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="任务状态" align="center" prop="code">
          <template slot-scope="scope">
            <span v-for="dict in dict.type.taskstatus" :key="dict.value">
              <el-tag
                v-if="scope.row.code == dict.value"
                :type="dict.raw.listClass"
              >
                <!-- {{ scope.row.taskStatus }} -->
                {{ dict.label }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" />
        <el-table-column label="结束时间" align="center" prop="endTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleRepair(scope.row)"
              :disabled="scope.row.code == 2"
              v-hasPermi="['console:dataTaskconf:Repair']"
              >修复</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleCheck(scope.row)"
              :disabled="scope.row.code == 2"
              v-hasPermi="['console:tasks:check']"
              >校验</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="asyncResult = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="同步结果"
      :visible.sync="codeEditorOpen"
      width="80%"
      destroy-on-close
    >
      <div class="codeBox">
        <div class="left">
          <el-divider content-position="left"><h2>源DDL</h2></el-divider>
          <CodeEditor
            :editorHight="250"
            :readOnly="true"
            :codeData="codeEditor.sourceCode"
          />
        </div>
        <div class="line">
          <svg
            t="1722844374330"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="7388"
            width="50"
            height="50"
          >
            <path
              d="M938.666667 512L640 761.6V262.4z"
              fill="#8a8a8a"
              p-id="7389"
            ></path>
            <path
              d="M128 426.666667h576v170.666666H128z"
              fill="#8a8a8a"
              p-id="7390"
            ></path>
          </svg>
        </div>
        <div class="right">
          <el-divider content-position="left"><h2>目标DDL</h2></el-divider>
          <CodeEditor
            ref="codeEditor"
            :editorHight="250"
            :codeData="codeEditor.sinkCode"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          v-loading="repairLoading"
          @click="handleRunDll"
          >修 复</el-button
        >
        <el-button type="primary" @click="codeEditorOpen = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="堆栈错误信息"
      :visible.sync="dialogStackVisible"
      width="75%"
    >
      <pre><code>{{ stackErrorsMsg }}</code></pre>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStackVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDataTaskconf,
  delDataTaskconf,
  addDataTaskconf,
  updateDataTaskconf,
  delDataTaskconfVerify,
} from "@/api/console/dataTaskconf";

import CodeEditor from "@/components/CodeEditor/index.vue";


import {
  dataTaskconfScheduler,
  dataTaskconfExecute,
  dataTaskLogGetNew,
  dataTaskLogGetNewLog,
} from "@/api/console/tasks";
import { sqlTaskExecuteSql } from "@/api/console/executeSql";

export default {
  name: "DataTaskconf",
  dicts: [
    "data_status",
    "synchronous_tasktype",
    "taskstatus",
    "data_base_type",
    "synchronous_jobmode",
    "all_tasktype",
    "appraise_taskmode",
  ],
  components: { CodeEditor },
  data() {
    return {
      codeEditor: {
        sourceCode: "",
        sinkCode: "",
      },
      codeEditorOpen: false,
      dialogStackVisible: false,
      asyncResultTable: null,
      stackErrorsMsg: "", // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务配置表格数据
      dataTaskconfList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pgNum: 1,
        pgSize: 10,
        taskName: null,
        taskType: null,
        sourceName: null,
        sinkName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      isLog: false,
      logFofText: [],
      timer: null,
      listTimer: null,
      asyncResult: false,
      verifyData: null,
      repairLoading: false,
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getList();
      vm.listTimer = setInterval(() => {
        vm.getList();
      }, 3000);
    });
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(this.listTimer);
    this.listTimer = null;
    next();
  },
  methods: {
    getIndex($index) {
      return (
        (this.queryParams.pgNum - 1) * this.queryParams.pgSize + $index + 1
      );
    },
    async handleRunDll() {
      this.repairLoading = true;
      try {
        await sqlTaskExecuteSql({
          datasourceId: this.verifyData.id,
          sqlContext: this.$refs.codeEditor._data.content,
        });
        this.$message.error("修复成功");
        this.repairLoading = false;
        this.codeEditorOpen = false;
      } catch (error) {
        this.$message.error(error);
        this.repairLoading = false;
      }
    },
    handleStack(row) {
      if (!row.errors) {
        return this.$message.warning("暂无错误信息");
      }
      this.dialogStackVisible = true;
      this.stackErrorsMsg = row.errors;
    },
    async handleRepair(row) {
      this.codeEditorOpen = true;
      this.codeEditor.sourceCode = row.sourceDdl;
      this.codeEditor.sinkCode = row.sinkDdl || "";
    },
    async handleTaskResult(row) {
      this.verifyData = row;
      this.asyncResult = true;
      let res = await dataTaskLogGetNew({
        jobType: row.jobType,
        taskId: row.id,
      });
      window.open(
        `/report/migrationReport?taskId=${row.id}&&id=${res.data.id}`
      );
      return;
      // const tableData = JSON.parse(res.data.taskResult);
      // this.asyncResultTable = tableData;
      // if (tableData.items.length > 0) {
      //   return;
      // }
      // let newTableData = [];
      // Object.keys(tableData.data).forEach((f) => {
      //   tableData.data[f].items.forEach((j) => {
      //     newTableData.push({
      //       ...j,
      //       taskType: f,
      //     });
      //   });
      // });
      // this.asyncResultTable.items = newTableData;
    },
    handleClose() {
      this.logFofText = [];
      clearInterval(this.timer);
      this.timer = null;
      this.isLog = false;
    },
    async handleResultLog(row) {
      this.isLog = true;
      this.logFofText = [];
      let that = this;
      let res = await dataTaskLogGetNew({
        jobType: row.jobType,
        taskId: row.id,
      });
      let logText = JSON.parse(res.data.taskLog);
      logText.forEach((f) => {
        this.logFofText.push({
          text: `${f.time}：${f.logMsg}`,
          logLevel: f.logLevel,
        });
      });
      this.$nextTick(() => {
        let scrollElem = that.$refs.logBox;
        scrollElem.scrollTo({
          top: scrollElem.scrollHeight,
          behavior: "smooth",
        });
      });
      if (res.data.taskStatus == 0 || res.data.jobType == "SYNC_DATA") {
        // this.logFofText = [];
        that.timer = setInterval(async () => {
          res = await dataTaskLogGetNewLog({
            id: res.data.id,
          });
          if (res.data.taskStatus != 0) {
            clearInterval(that.timer);
            that.timer = null;
            let res = await dataTaskLogGetNew({
              jobType: row.jobType,
              taskId: row.id,
            });
            let logText = JSON.parse(res.data.taskLog);
            this.logFofText = [];
            logText.forEach((f, i) => {
              if (f.logMsg.includes(logText[i])) return;
              this.logFofText.push({
                text: `${f.time}：${f.logMsg}`,
                logLevel: f.logLevel,
              });
            });
            this.$nextTick(() => {
              let scrollElem = that.$refs.logBox;
              scrollElem.scrollTo({
                top: scrollElem.scrollHeight,
                behavior: "smooth",
              });
            });
            return;
          }
          JSON.parse(res.data.taskLog).forEach((f) => {
            this.logFofText.push({
              text: `${f.time}：${f.logMsg}`,
              logLevel: f.logLevel,
            });
          });
          this.$nextTick(() => {
            let scrollElem = that.$refs.logBox;
            scrollElem.scrollTo({
              top: scrollElem.scrollHeight,
              behavior: "smooth",
            });
          });
        }, 1000);
      } else {
        clearInterval(this.timer);
        this.timer = null;
        return;
      }
    },
    handleResult(row) {
      this.$router.push({
        path: "/reports/index",
        query: { id: row.id, jobType: row.jobType, type: "dataTaskconf" },
      });
    },
    handleEnter() {
      clearInterval(this.timer);
      this.timer = null;
      this.isLog = false;
      return;
    },
    /** 查询任务配置列表 */
    getList() {
      this.loading = false;
      listDataTaskconf(this.queryParams).then((response) => {
        this.dataTaskconfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskType: null,
        sourceId: null,
        sourceName: null,
        sinkId: null,
        sinkName: null,
        jobId: null,
        cdcId: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pgNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: "/synchronous/synchronousAdd" });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: "/synchronous/synchronousAdd",
        query: { id: row.id },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDataTaskconf(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDataTaskconf(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;

      this.$modal
        .confirm('是否确认删除任务配置编号为"' + ids + '"的数据项？')
        .then(function () {
          return delDataTaskconf({ idArray: Array.isArray(ids) ? ids : [ids] });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleCheck(row) {
      let that = this;
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认校验配置编号为"' + that.verifyData.id + '"的数据项？')
        .then(function () {
          return delDataTaskconfVerify({
            id: that.verifyData.id,
            taskTypeScope: row.type,
            name: row.objectName,
          });
        })
        .then(() => {
          // this.getList();
          this.$modal.msgSuccess("校验成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "console/dataTaskconf/export",
        {
          ...this.queryParams,
        },
        `dataTaskconf_${new Date().getTime()}.xlsx`
      );
    },
    handleScheduler(row) {
      let that = this;
      let ids = row.id || this.ids;
      this.$modal.confirm("是否确认启动调度器？").then(function () {
        dataTaskconfScheduler({
          idArray: Array.isArray(ids) ? ids : [ids],
        })
          .then((res) => {
            that.$message.success("调度器启动成功");
          })
          .catch((err) => {
            that.$message.error("调度器启动失败");
          });
      });
    },
    handleExecute(row) {
      let that = this;
      let ids = row.id || this.ids;
      this.$modal.confirm("是否确认立即执行？").then(function () {
        const loading = that.$loading({
          lock: true,
          text: "执行中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        dataTaskconfExecute({
          id: ids,
        })
          .then((res) => {
            loading.close();
            that.$message.success("任务提交成功");
          })
          .catch((err) => {
            loading.close();
            that.$message.error("执行失败");
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
h2 {
  margin: 0;
}

pre {
  height: 400px;
  overflow: auto;
}

.codeBox {
  display: flex;
  align-items: center;
  justify-content: space-around;
  .left,
  .right {
    width: 45%;
  }

  .line {
    width: 5%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.textBox {
  height: 300px;
  overflow-y: auto;
}
</style>
